<?php
namespace App\Http\Controllers\Client\Activity;

use App\Http\Controllers\ClientController;
use App\Models\Common\Common;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LotteryConsumeController extends ClientController
{
    /**
     * 商家核销霸王餐
     */
    public function index()
    {

        $all = $this->all;
        $act_id = $all['act_id'];

        try{
            DB::beginTransaction();

            // 查询活动信息
            $activity = DB::table('lottery_activity')->where('act_id','=',$act_id)->lockForUpdate()->first();
            $activity = json_decode(json_encode($activity), true);

            if($activity['creator'] !== $this->we_id){
                DB::rollBack();
                return $this->setReturnJson(-1,'不是您的活动，无法核销');
            }

            $shop_type = DB::table('shop')->where('shop_id','=',$activity['shop_id'])->value('shop_type');
            // 查询商家的霸王餐活动in_use数量
            $remaining = DB::table('lottery_remaining')->where('we_id','=',$activity['creator'])->where('st_id','=',$shop_type)->lockForUpdate()->first();
            $remaining = json_decode(json_encode($remaining), true);
            if($remaining['in_use_times'] < 1){
                DB::rollBack();
                Log::emergency('核销数据错误：商家余量不足',['activity'=>$activity,'remaining'=>$remaining]);
                return $this->setReturnJson(-1,'数据错误，请联系在线客服处理');
            }

            // 修改活动状态
            DB::table('lottery_activity')->where('act_id','=',$act_id)->update(['status'=>Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_SUCCESS]);
            // 修改开奖状态
            DB::table('lottery_draw_detail')->where('act_id','=',$act_id)->update(['consumed'=>1,'consumed_at'=>date('Y-m-d H:i:s')]);
            // 修改用户存量
            DB::table('lottery_remaining')->where('we_id','=',$activity['creator'])->where('st_id','=',$shop_type)->decrement('in_use_times');
            // 记录日志
            DB::table('lottery_remaining_log')->insert([
                'lr_id'=>$remaining['lr_id'],
                'action'=>4, // 核销
                'action_num'=>1,
                'rest_num'=>$remaining['remaining_times'],
                'in_use_num'=>$remaining['in_use_times'] - 1,
            ]);

            $message = DB::table('lottery_activity as la')
                ->leftJoin('lottery_draw_detail as ldd','la.act_id','=','ldd.act_id')
                ->leftJoin('lottery_users_draw as lud','ldd.participate_id','=','lud.participate_id')
                ->leftJoin('lottery_users as lu','ldd.we_id','=','lu.we_id')
                ->leftJoin('shop','la.shop_id','=','shop.shop_id')
                ->where('la.act_id','=',$act_id)
                ->select('lu.openid','lud.code','shop.shop_name')
                ->get()
                ->toArray();
            $message = json_decode(json_encode($message), true);
            $message = $message[0];
            // 核销成功通知   consume
            $data = [
                'first' => '商家已确认核销您的霸王餐信息',
                'keyword1' => $message['code'],
                'keyword2' => date('Y-m-d H:i:s'),
                'keyword3' => $message['shop_name'],
                'remark' => '如果商家的核销操作您不知情，请致电商家进行询问。',
            ];
            Common::sendLaifeiMessage($message['openid'], 'consume', $data, '/lottery/mine?active=3');

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(LotteryConsumeController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '核销失败');
        }
        return $this->setReturnJson(0,'霸王餐核销成功，请自行监督达人发布评论');

    }

}
